<?php
/**
 * Created by PhpStorm.
 * User: lingyun
 * Date: 2018/5/11
 * Time: 17:15
 * Desc: 收货地址管理
 */
namespace app\index\controller;
use think\Controller;
use think\Db;
use app\index\controller\Base;
use app\index\service\WeixinService;
use pinyin\Pinyin;
use app\comm\service\DadaOpenapi;

class Address extends Base{
    //当前选择的城市
    public $city = '';

    public function _initialize()
    {
        parent::_initialize();
        if (empty(session('_user_uid_.uid'))) {
            $url = url('Login/loginin') . "?c=user&a=index";       //登陆完成跳转回来的url
            $this->redirect($url);       //登录
        }
        $this->assign('realname', session('_user_uid_.realname'));
    }

    /**
     * @Author  lingyun
     * @Desc    首页
     */
    public function index(){
        $uid = session('_user_uid_.uid');
        $sql = "SELECT id,name,logo,cat_id FROM ys_goods AS a WHERE 5> (SELECT COUNT(*) FROM ys_goods WHERE cat_id=a.cat_id AND id>a.id) AND a.is_online=1 ORDER BY a.id DESC";
        $tui_goods = Db::query($sql);
        $user = Db::name('user')->where('uid',$uid)->find();        //会员信息
        $store = db('store')->where('id',cookie('store_id'))->find();
        $level_info = get_user_level($user['level_id']);         //会员的等级信息
        $user['mobile'] = substr_replace($user['mobile'],'****',3,4);
        $category = get_top_category();           //商品顶级分类
        $exp_category = get_exp_category();       //商品扩展分类
        $city = db('city')->where(['is_deleted'=>0,'status'=>1])->select();
        $address = db('user_address')->where(['uid'=>session('_user_uid_.uid'),'deleted'=>0])->select();

        $this->assign('user',$user);                    //会员信息
        $this->assign('store',$store);                    //会员信息
        $this->assign('level_info',$level_info);        //会员等级信息
        $this->assign('tui_goods',$tui_goods);
        $this->assign('category',$category);
        $this->assign('exp_category',$exp_category);
        $this->assign('cur_lanmu',3);
        $this->assign('city',$city);
        $this->assign('address',$address);

        return $this->fetch();
    }

    /**
     * @Author  lingyun
     * @Desc    添加 -- 编辑收货地址
     * 2018-05-11
     */
    public function add_edit(){
        $request = request();
        if($request->isPost()){
            $post = input('post.');

            $reg = "/^1([358][0-9]|4[579]|66|7[0135678]|9[89])[0-9]{8}$/";
            if($post['consignee'] == ''){
                $this->error('请填写联系人','');
            }
            if($post['mobile'] == ''){
                $this->error('请填写联系手机号','');
            }
            if($post['address'] == ''){
                $this->error('请填写详细收货地址','');
            }
            if($post['city'] == ''){
                $this->error('请选择所在城市','');
            }

            if(!preg_match($reg,$post['mobile'])){
                $this->error('手机格式输入错误','');
            }
            $res = $this->count_delivery_fee($post['address']);
            if($res['code'] == 0){
                $this->error($res['msg'],'');
            }

            if(empty($post['id'])){     //新增
                if($post['is_default'] == 1){
                    db('user_address')->where('uid',session('_user_uid_.uid'))->update(['is_default'=>0]);
                }
                $data_arr = [
                    'uid'=>session('_user_uid_.uid'),
                    'consignee'=>$post['consignee'],
                    'mobile'=>$post['mobile'],
                    'city'=>$post['city'],
                    'address'=>$post['address'],
                    'is_default'=>$post['is_default'],
                    'addtime'=>time()
                ];
                $falg = db('user_address')->insert($data_arr);
                $falg>0?$this->success('保存成功',''):$this->error('保存失败');
            }else{
                if($post['is_default'] == 1){
                    db('user_address')->where('uid',session('_user_uid_.uid'))->update(['is_default'=>0]);
                }
                $data_arr = [
                    'consignee'=>$post['consignee'],
                    'mobile'=>$post['mobile'],
                    'city'=>$post['city'],
                    'address'=>$post['address'],
                    'is_default'=>$post['is_default'],
                ];
                $falg = db('user_address')->where('id',$post['id'])->update($data_arr);
                $falg!==false?$this->success('保存成功',''):$this->error('保存失败');
            }
        }else{
            $id = input('id');
            $info = db('user_address')->where('id',$id)->find();
            $city = db('city')->where(['status'=>1,'is_deleted'=>0])->select();

            $this->assign('info',$info);
            $this->assign('city',$city);
            return $this->fetch();
        }
    }

    /**
     * @Author  lingyun
     * @Desc    移动端添加 -- 编辑收货地址
     * 2018-05-16
     */
    public function m_add_edit(){
        $request = request();
        if($request->isPost()){
            $post = input('post.');

            $reg = "/^1([358][0-9]|4[579]|66|7[0135678]|9[89])[0-9]{8}$/";
            if($post['consignee'] == ''){
                $this->error('请填写联系人','');
            }
            if($post['mobile'] == ''){
                $this->error('请填写联系手机号','');
            }
            if($post['address'] == ''){
                $this->error('请填写详细收货地址','');
            }
            if($post['city'] == ''){
                $this->error('请选择所在城市','');
            }

            if(!preg_match($reg,$post['mobile'])){
                $this->error('手机格式输入错误','');
            }
            $res = $this->count_delivery_fee($post['address']);
            if($res['code'] == 0){
                $this->error($res['msg'],'');
            }

            if(empty($post['id'])){     //新增
                if($post['is_default'] == 1){
                    db('user_address')->where('uid',session('_user_uid_.uid'))->update(['is_default'=>0]);
                }
                $data_arr = [
                    'uid'=>session('_user_uid_.uid'),
                    'consignee'=>$post['consignee'],
                    'mobile'=>$post['mobile'],
                    'city'=>$post['city'],
                    'address'=>$post['address'],
                    'is_default'=>$post['is_default'],
                    'addtime'=>time()
                ];
                $falg = db('user_address')->insert($data_arr);
                $falg>0?$this->success('保存成功',''):$this->error('保存失败');
            }else{
                if($post['is_default'] == 1){
                    db('user_address')->where('uid',session('_user_uid_.uid'))->update(['is_default'=>0]);
                }
                $data_arr = [
                    'consignee'=>$post['consignee'],
                    'mobile'=>$post['mobile'],
                    'city'=>$post['city'],
                    'address'=>$post['address'],
                    'is_default'=>$post['is_default'],
                ];
                $falg = db('user_address')->where('id',$post['id'])->update($data_arr);
                $falg!==false?$this->success('保存成功',''):$this->error('保存失败');
            }
        }else{
            $id = input('id');
            $info = db('user_address')->where('id',$id)->find();
            $city = db('city')->where(['status'=>1,'is_deleted'=>0])->select();
            $uid = session('_user_uid_.uid');
            $sql = "SELECT id,name,logo,cat_id FROM ys_goods AS a WHERE 5> (SELECT COUNT(*) FROM ys_goods WHERE cat_id=a.cat_id AND id>a.id) AND a.is_online=1 ORDER BY a.id DESC";
            $tui_goods = Db::query($sql);
            $user = Db::name('user')->where('uid',$uid)->find();        //会员信息
            $store = db('store')->where('id',cookie('store_id'))->find();
            $level_info = get_user_level($user['level_id']);         //会员的等级信息
            $user['mobile'] = substr_replace($user['mobile'],'****',3,4);
            $category = get_top_category();           //商品顶级分类
            $exp_category = get_exp_category();       //商品扩展分类
            $city = db('city')->where(['is_deleted'=>0,'status'=>1])->select();

            $this->assign('user',$user);                    //会员信息
            $this->assign('store',$store);                    //会员信息
            $this->assign('level_info',$level_info);        //会员等级信息
            $this->assign('tui_goods',$tui_goods);
            $this->assign('category',$category);
            $this->assign('exp_category',$exp_category);
            $this->assign('cur_lanmu',3);
            $this->assign('city',$city);

            $this->assign('info',$info);
            $this->assign('city',$city);
            return $this->fetch();
        }
    }

    /**
     * @Author  lingyun
     * @Desc    计算运费
     * @Param   $address    收货地址
     */
    public function count_delivery_fee($address=''){
        $root = request()->domain();
        $config_arr = config('dada');
        $config_arr['url'] = "http://newopen.imdada.cn/api/order/queryDeliverFee";          //订单详情查询
        $dada_obj = new DadaOpenapi($config_arr);
        $data_arr['origin_id'] = build_order_no().cookie('store_id');
        $store = db('store')->alias('a')->join('ys_city b','a.city_code=b.code','LEFT')->where('a.id',cookie('store_id'))->field('a.*,b.dada_code')->find();            //门店信息
        $data_arr['shop_no'] = $store['dada'];           //门店编号
        $data_arr['city_code'] = $store['dada_code'];           //门店编号
        $data_arr['cargo_price'] = 0.01;           //订单金额
        $data_arr['is_prepay'] = 0;           //是否需要垫付，0否
        $data_arr['receiver_name'] = '一朵';           //是否需要垫付，0否
        $data_arr['receiver_address'] = $address;           //收货地址
        $data_arr['callback'] = $root.'/index.php/index/dada/count_delivery_fee';           //是否需要垫付，0否
        $data_arr['receiver_phone'] = '18757685769';           //是否需要垫付，0否
        $fee_info = $dada_obj->pre_count_delevety_fee($data_arr);          //与计算订单运费
        $result = json_decode($fee_info,true);
        if(empty($result)){
            return ['code'>0,'msg'=>'地址填写错误或不在配送范围，请检查并核实'];
        }else if($result['status'] =='fail' && $result['code'] != 0){
            return ['code'>0,'msg'=>'地址填写错误或不在配送范围，请检查并核实'];
//           $this->error('地址填写错误或不在配送范围，请检查并核实','');
        }

        $price = $this->getDeliveryFee($result['result']['distance']);

        return ['code'=>1,'msg'=>$price['msg']];

    }

    /**
     * @Author  lingyun
     * @Desc    计算运费
     * @param $distance
     * @return array
     */
    private function getDeliveryFee($distance){
        $distance = $distance/2/500;
        //查询运费信息
        $data = Db::name('delivery_fee')->where('is_deleted',0)->order('distance asc')->select();
        foreach($data as $k => $v){
            if($distance < $v['distance']){
                return ['code'=>1,'msg'=>$v['price']];
                break;
            }
        }
        $val = end($data);
        return ['code'=>1,'msg'=>$val['price']];
    }

    /**
     * @Author  lingyun
     * @Desc    设置默认地址
     * 2018-05-16
     */
    public function set_default(){
        $id = input('id');
        db('user_address')->where('uid',session('_user_uid_.uid'))->update(['is_default'=>0]);
        $res = db('user_address')->where('id',$id)->update(['is_default'=>1]);
        $res!==false?$this->success('保存成功',''):$this->error('保存失败，请稍后再试','');
    }

    /**
     * @Author  lingyun
     * @Desc    删除地址
     */
    public function del_address(){
        $id = input('id');
        $res = db('user_address')->where('id',$id)->delete();
        $res>0?$this->success('删除成功',''):$this->error('删除失败,请稍后再试','');
    }


}
